package fileService;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import android.util.Log;

public class FileReceiverService {
	private SSLServerSocket fileService;
	
	public void startReceiveFileService() throws IOException{
		Log.i("FileReceiverService","startReceiveFileService()");
		SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
		fileService = (SSLServerSocket) factory.createServerSocket(2083);
		fileService.setEnabledCipherSuites(fileService.getSupportedCipherSuites());
//		fileService = new ServerSocket(2083);
	}
	public void stopReceiveFileService() throws IOException{
		Log.i("FileReceiverService","stopReceiveFileService()");
		fileService.close();
	}	
	public SSLSocket receiveFileConnection() throws IOException{
		Log.i("FileReceiverService","receiveFileConnection()");
		SSLSocket client = (SSLSocket) fileService.accept();
		return client;
	}	
	
	public CSFileWrapper receiveFile(SSLSocket client, String fileName, int fileSize) throws IOException{
		Log.i("FileReceiverService","receiveFile()");
		DataInputStream dis = new DataInputStream(new BufferedInputStream(client.getInputStream()));

		byte[] fileData = new byte[fileSize];
		
		if(fileSize > 0){
			dis.readFully(fileData);
		}
		
		CSFileWrapper file = new CSFileWrapper();
		file.setData(fileData);
		file.setFileName(fileName);

		dis.close();		
		return file;
	}
	public void sendFile(byte[] data, InetAddress client) throws UnknownHostException, IOException{
		Log.i("FileReceiverService","sendFile()");
		SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
		SSLSocket toClient = (SSLSocket) factory.createSocket(client, 2083);
		toClient.setEnabledCipherSuites(toClient.getSupportedCipherSuites());
		toClient.startHandshake();
//		Socket toClient = new Socket(client, 2083);
		
		OutputStream os = toClient.getOutputStream();
		os.write(data);
		os.flush();
		os.close();
		toClient.close();
	}
}
